package crp.core.workflow.domain.services;

import com.qwlabs.cdi.DispatchInstance;
import com.qwlabs.cdi.Dispatchable;
import com.qwlabs.cdi.Primary;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import java.util.Map;
import java.util.Objects;

@ApplicationScoped
@Primary
public class WorkflowExternalInfoSearcherCombiner implements WorkflowExternalInfoSearcher {

    private final DispatchInstance<String, WorkflowExternalInfoSearcher> instance;

    @Inject
    public WorkflowExternalInfoSearcherCombiner(Instance<WorkflowExternalInfoSearcher> instance) {
        this.instance = DispatchInstance.of(instance);
    }

    @Override
    public Map<String, Object> externalInfo(String externalId, String topic) {
        Objects.requireNonNull(topic, "topic can not be null.");
        Objects.requireNonNull(externalId, "externalId can not be null.");
        return this.instance.getOptional(topic).map(searcher -> searcher.externalInfo(externalId, topic)).orElseThrow();
    }
}
